<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    class="meeting-form"
  >
    <el-form-item label="会议名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入会议名称" style="width: 300px" />
    </el-form-item>

    <el-form-item label="会议类型" prop="type">
      <el-select v-model="formData.type" placeholder="请选择会议类型" style="width: 300px">
        <el-option
          v-for="type in meetingTypes"
          :key="type.value"
          :label="type.label"
          :value="type.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="会议时间" prop="timeRange" style="width: 400px">
      <el-date-picker
        v-model="timeRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        style="width: 150px"
        @change="handleTimeRangeChange"
      />
    </el-form-item>

    <el-form-item label="会议地点" prop="location">
      <el-input v-model="formData.location" placeholder="请输入会议地点" style="width: 300px" />
    </el-form-item>

    <el-form-item label="线上直播" prop="isOnline">
      <el-switch v-model="formData.isOnline" />
    </el-form-item>

    <el-form-item label="会议描述" prop="description">
      <el-input
        v-model="formData.description"
        type="textarea"
        :rows="3"
        placeholder="请输入会议描述"
        style="width: 300px"
      />
    </el-form-item>

    <el-form-item label="会议议程">
      <div class="agenda-section">
        <div class="agenda-header">
          <el-button type="primary" @click="openAgendaDialog()">
            <el-icon><Plus /></el-icon>添加议程
          </el-button>
        </div>
        
        <el-table v-if="agendaItems.length" :data="agendaItems" style="width: 100%">
          <el-table-column label="时间" width="300">
            <template #default="{ row }">
              {{ row.startTime }} - {{ row.endTime }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="议题" />
          <el-table-column prop="speaker" label="主讲人" width="150" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="openAgendaDialog(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="danger" link @click="deleteAgendaItem(row.id)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无议程安排" />
      </div>
    </el-form-item>

    <el-form-item label="封面图片" prop="coverImage">
      <el-upload
        class="meeting-cover-upload"
        :auto-upload="false"
        :show-file-list="true"
        :limit="1"
        accept="image/*"
        :on-change="handleCoverImageChange"
        :on-remove="handleCoverImageRemove"
        list-type="picture-card"
      >
        <template #default>
          <el-icon><Plus /></el-icon>
          <div class="el-upload__text">点击上传</div>
        </template>
        <template #file="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><ZoomIn /></el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="() => handleCoverImageRemove()">
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 JPG/PNG/GIF 格式图片，大小不超过 2MB，宽高不超过1600px
          </div>
        </template>
      </el-upload>
    </el-form-item>

    <el-form-item label="相关文件">
      <el-upload
        class="meeting-file-upload"
        :auto-upload="false"
        :file-list="fileList"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :on-error="handleUploadError"
        multiple
      >
        <el-button type="primary">上传文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持任意格式文件，单个文件不超过100MB
          </div>
        </template>
      </el-upload>
    </el-form-item>

    <el-form-item label="会议视频">
      <div class="video-upload-section">
        <el-upload
          ref="uploadRef"
          class="meeting-video-upload"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          :before-upload="beforeVideoUpload"
          :on-change="handleVideoChange"
          :on-remove="handleVideoRemove"
          :on-error="handleUploadError"
          accept="video/*"
        >
          <el-button type="primary">上传视频</el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持mp4、webm等常见视频格式，单个文件不超过500MB
            </div>
          </template>
        </el-upload>
        
        <div v-if="formData.videoUrl" class="video-preview">
          <video 
            :src="formData.videoUrl" 
            controls 
            style="max-width: 100%; max-height: 300px;"
          />
        </div>
      </div>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>

  <!-- 议程编辑弹窗 -->
  <el-dialog
    v-model="agendaDialogVisible"
    :title="isEditingAgenda ? '编辑议程' : '添加议程'"
    width="600px"
  >
    <el-form label-width="100px">
      <el-form-item label="时间范围" required>
        <el-time-picker
          v-model="currentAgendaItem.startTime"
          format="HH:mm"
          placeholder="开始时间"
        />
        <span class="mx-2">-</span>
        <el-time-picker
          v-model="currentAgendaItem.endTime"
          format="HH:mm"
          placeholder="结束时间"
        />
      </el-form-item>
      
      <el-form-item label="议题" required>
        <el-input v-model="currentAgendaItem.title" placeholder="请输入议题" style="width: 300px" />
      </el-form-item>
      
      <el-form-item label="主讲人">
        <el-input v-model="currentAgendaItem.speaker" placeholder="请输入主讲人" style="width: 300px" />
      </el-form-item>
      
      <el-form-item label="详细说明">
        <el-input
          v-model="currentAgendaItem.description"
          type="textarea"
          :rows="3"
          placeholder="请输入详细说明"
          style="width: 300px"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="agendaDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAgendaSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 图片预览对话框 -->
  <el-dialog v-model="previewVisible" append-to-body width="800px" align-center>
    <img w-full :src="previewUrl" alt="Preview Image" style="max-width: 100%; height: auto;" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { FormInstance, UploadProps, UploadFile } from 'element-plus'
import { Plus, Delete, Edit, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { 
  MeetingType, 
  Meeting, 
  MeetingFile, 
  AgendaItem,
  deleteMeetingFile,
  uploadMeetingFile,
  deleteMeetingVideo,
  uploadMeetingVideo,
  uploadMeetingImage
} from '@/api/meeting'

// 简化的MeetingFile接口，只包含name和url属性
interface SimpleMeetingFile {
  name: string;
  url: string;
}

const props = defineProps<{
  meeting?: Meeting
}>()

const emit = defineEmits<{
  (e: 'submit', formData: Partial<Meeting>): void
  (e: 'cancel'): void
}>()

const formRef = ref<FormInstance>()
const fileList = ref<any[]>([])
const agendaDialogVisible = ref(false)
const agendaItems = ref<AgendaItem[]>([])
const currentAgendaItem = ref<AgendaItem>({
  id: '',
  startTime: '',
  endTime: '',
  title: '',
  speaker: '',
  description: ''
})
const isEditingAgenda = ref(false)
const uploadRef = ref()

// 为了直接上传文件，添加这两个ref
const coverImageFile = ref<File | null>(null)
const meetingFiles = ref<File[]>([])
const meetingVideos = ref<File[]>([])

// 添加图片预览对话框需要的状态
const previewVisible = ref(false)
const previewUrl = ref('')

const meetingTypes = [
  { label: '主论坛', value: MeetingType.MAIN },
  { label: '平行会议', value: MeetingType.PARALLEL },
  { label: '科普论坛', value: MeetingType.SCIENCE },
  { label: '新品发布', value: MeetingType.PRODUCT },
  { label: '生态合作论坛', value: MeetingType.ECOLOGY }
]

const formData = ref<Partial<Meeting>>({
  name: '',
  type: MeetingType.MAIN,
  begin: '',
  end: '',
  location: '',
  description: '',
  isOnline: true,  // 使用布尔值true替代数字1
  coverImage: '',
  files: [],
  agenda: '[]',
  videoUrl: ''
})

const timeRange = ref<[string, string]>(
  props.meeting ? 
  [props.meeting.begin, props.meeting.end] : 
  ['', '']
)

// 如果是编辑模式，初始化表单数据
if (props.meeting) {
  formData.value = {
    ...formData.value,
    ...props.meeting,
    begin: props.meeting.begin,
    end: props.meeting.end,
    // 确保isOnline为布尔值
    isOnline: typeof props.meeting.isOnline === 'boolean' 
      ? props.meeting.isOnline 
      : props.meeting.isOnline
  }
  if (props.meeting.files) {
    fileList.value = props.meeting.files.map(file => ({
      name: file.name,
      url: file.url
    }))
  }
}

const rules = {
  name: [{ required: true, message: '请输入会议名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择会议类型', trigger: 'change' }],
  timeRange: [{ required: true, message: '请选择会议时间', trigger: 'change' }],
  begin: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  end: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
  description: [{ required: true, message: '请输入会议描述', trigger: 'blur' }]
}

// const uploadAction = '/api/upload' // 替换为实际的上传接口

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  
  // 保存文件引用以便后续手动上传
  coverImageFile.value = file
  
  // 创建一个临时URL用于预览
  formData.value.coverImage = URL.createObjectURL(file)
  
  // 阻止自动上传
  return false
}

const handleCoverSuccess = (response: any) => {
  formData.value.coverImage = response.url
  ElMessage.success('封面上传成功')
}

const handleFileSuccess = (response: any) => {
  const newFile: MeetingFile = {
    id: response.id,
    name: response.name,
    url: response.url,
    size: response.size,
    uploadTime: response.uploadTime
  }
  if (!formData.value.files) {
    formData.value.files = []
  }
  formData.value.files.push(newFile)
  ElMessage.success('文件上传成功')
}

const handleFileRemove = async (file: MeetingFile) => {
  try {
    await deleteMeetingFile({
      meetId: String(props.meeting?.id || ''),
      fileUrl: file.url
    })
    ElMessage.success('文件删除成功')
    // 更新文件列表
    if (formData.value.files) {
      formData.value.files = formData.value.files.filter(f => f.id !== file.id)
    }
  } catch (error) {
    console.error('文件删除失败:', error)
    ElMessage.error('文件删除失败')
  }
}

const handleFileDownload = async (file: MeetingFile) => {
  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = file.url
    link.setAttribute('download', file.name)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('文件下载失败:', error)
    ElMessage.error('文件下载失败')
  }
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const openAgendaDialog = (item?: AgendaItem) => {
  if (item) {
    currentAgendaItem.value = { ...item }
    isEditingAgenda.value = true
  } else {
    currentAgendaItem.value = {
      id: String(Date.now()),
      startTime: '',
      endTime: '',
      title: '',
      speaker: '',
      description: ''
    }
    isEditingAgenda.value = false
  }
  agendaDialogVisible.value = true
}

const handleAgendaSubmit = () => {
  if (!currentAgendaItem.value.startTime || !currentAgendaItem.value.endTime || !currentAgendaItem.value.title) {
    ElMessage.warning('请填写必要的议程信息')
    return
  }

  if (isEditingAgenda.value) {
    const index = agendaItems.value.findIndex(item => item.id === currentAgendaItem.value.id)
    if (index !== -1) {
      agendaItems.value[index] = { ...currentAgendaItem.value }
    }
  } else {
    agendaItems.value.push({ ...currentAgendaItem.value })
  }
  
  agendaDialogVisible.value = false
  // 更新表单中的议程字段（JSON格式）
  formData.value.agenda = JSON.stringify(agendaItems.value)
}

const deleteAgendaItem = (id: string) => {
  agendaItems.value = agendaItems.value.filter(item => String(item.id) !== String(id))
  formData.value.agenda = JSON.stringify(agendaItems.value)
}

// 初始化议程数据
if (props.meeting?.agenda) {
  try {
    agendaItems.value = JSON.parse(props.meeting.agenda)
  } catch (e) {
    console.warn('Invalid agenda format:', e)
  }
}

const handleTimeRangeChange = (val: [string, string] | null) => {
  console.log('时间范围变更:', val);
  if (val && val.length === 2) {
    formData.value.begin = val[0]
    formData.value.end = val[1]
    // 设置timeRange字符串，与后端格式一致
    formData.value.timeRange = `${val[0]},${val[1]}`
  } else {
    formData.value.begin = ''
    formData.value.end = ''
    formData.value.timeRange = undefined
  }
}

// 修改文件上传处理
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return
  
  // 检查文件大小（100MB）
  const maxSize = 100 * 1024 * 1024
  const isValidSize = file.size! <= maxSize
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 100MB！')
    return
  }
  
  // 保存文件引用以便后续手动上传
  meetingFiles.value.push(file.raw)
  
  // 创建一个临时文件对象用于预览
  if (!formData.value.files) {
    formData.value.files = []
  }
  
  // 添加到预览列表
  formData.value.files.push({
    id: String(Date.now()),
    name: file.name,
    url: URL.createObjectURL(file.raw),
    size: file.size || 0,
    uploadTime: new Date().toISOString()
  });
  
  return false
}

// 修改视频上传检查，简化功能，专注于记录调试信息
const beforeVideoUpload: UploadProps['beforeUpload'] = (file) => {
  console.log('beforeVideoUpload被调用:', file.name, file.type, file.size);
  
  // 所有验证逻辑移至handleVideoChange，这里只记录并返回false
  console.log('视频文件传递给handleVideoChange处理');
  
  // 阻止自动上传
  return false
}

const handleVideoChange = (file: UploadFile) => {
  console.log('handleVideoChange被调用:', file.name);
  if (!file.raw) return;
  
  // 检查视频格式
  const allowedTypes = ['video/mp4', 'video/webm', 'video/ogg']
  const isValidType = allowedTypes.includes(file.raw.type)
  if (!isValidType) {
    ElMessage.error('只支持 MP4、WebM、Ogg 格式的视频文件！')
    console.error('视频格式不支持:', file.raw.type);
    return false
  }
  
  // 检查文件大小（500MB）
  const maxSize = 500 * 1024 * 1024
  const isValidSize = file.raw.size <= maxSize
  if (!isValidSize) {
    ElMessage.error('视频文件大小不能超过 500MB！')
    console.error('视频文件过大:', file.raw.size);
    return false
  }
  
  // 保存文件引用以便后续手动上传 - 使用数组而不是单个引用
  meetingVideos.value.push(file.raw);
  console.log('视频文件已添加到meetingVideos数组，当前数量:', meetingVideos.value.length);
  console.log('视频文件详情:', {name: file.raw.name, type: file.raw.type, size: file.raw.size});
  
  // 创建一个临时URL用于预览
  formData.value.videoUrl = URL.createObjectURL(file.raw)
  
  return false
}

const handleVideoSuccess = async (response: any, uploadFile: UploadFile) => {
  try {
    if (response.code === 0 && response.url) {
      formData.value.videoUrl = response.url
      ElMessage.success('视频上传成功')
    } else {
      throw new Error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    ElMessage.error('视频上传失败：' + (error instanceof Error ? error.message : '未知错误'))
    // 移除上传失败的文件
    const upload = uploadRef.value
    if (upload) {
      upload.handleRemove(uploadFile)
    }
  }
}

const handleVideoRemove = async () => {
  if (!formData.value.videoUrl) return
  console.log('准备删除视频, URL:', formData.value.videoUrl);
  try {
    if (props.meeting?.id) {
      await deleteMeetingVideo({
        meetId: String(props.meeting.id),
        videoUrl: formData.value.videoUrl
      })
      console.log('视频删除成功');
      ElMessage.success('视频删除成功')
    }
    // 清空视频文件数组
    meetingVideos.value = [];
    formData.value.videoUrl = undefined
    console.log('视频引用已清除, meetingVideos数组长度 =', meetingVideos.value.length);
  } catch (error) {
    console.error('视频删除失败:', error)
    ElMessage.error('视频删除失败')
  }
}

// 添加图片压缩函数
const compressImage = (file: File, maxWidth = 1200, maxHeight = 1200, quality = 0.8): Promise<File> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target?.result as string
      img.onload = () => {
        // 计算压缩后的宽高，保持原始比例
        let width = img.width
        let height = img.height
        if (width > height) {
          if (width > maxWidth) {
            height = Math.round((height * maxWidth) / width)
            width = maxWidth
          }
        } else {
          if (height > maxHeight) {
            width = Math.round((width * maxHeight) / height)
            height = maxHeight
          }
        }
        
        // 创建canvas并绘制压缩后的图片
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d')
        if (!ctx) {
          reject(new Error('Failed to get canvas context'))
          return
        }
        ctx.drawImage(img, 0, 0, width, height)
        
        // 转换为Blob
        canvas.toBlob((blob) => {
          if (!blob) {
            reject(new Error('Failed to compress image'))
            return
          }
          // 创建新文件
          const compressedFile = new File([blob], file.name, {
            type: blob.type,
            lastModified: Date.now()
          })
          resolve(compressedFile)
        }, file.type, quality)
      }
      img.onerror = () => {
        reject(new Error('Failed to load image'))
      }
    }
    reader.onerror = () => {
      reject(new Error('Failed to read file'))
    }
  })
}

// 添加转换函数，将完整MeetingFile转换为SimpleMeetingFile
const convertToSimpleMeetingFiles = (files?: MeetingFile[]): SimpleMeetingFile[] => {
  if (!files || files.length === 0) return [];
  return files.map(file => ({
    name: file.name,
    url: file.url
  }));
};

// 修改uploadFilesAndGetFormData函数
const uploadFilesAndGetFormData = async (): Promise<Partial<Meeting>> => {
  try {
    // 创建一个新的表单数据对象
    const updatedFormData = { ...formData.value }
    console.log('开始处理表单数据，原始isOnline值:', updatedFormData.isOnline);
    
    // 添加timeRange字段
    if (updatedFormData.begin && updatedFormData.end) {
      updatedFormData.timeRange = `${updatedFormData.begin},${updatedFormData.end}`
      console.log('设置timeRange:', updatedFormData.timeRange);
    }
    
    // 转换isOnline为数字（0/1）
    if (updatedFormData.isOnline !== undefined) {
      // @ts-ignore - 类型错误可以忽略
      updatedFormData.isOnline = updatedFormData.isOnline ? 1 : 0;
      console.log('isOnline已转换为数字类型:', updatedFormData.isOnline);
    }
    
    // 1. 上传封面图片
    if (coverImageFile.value) {
      ElMessage.info('正在处理封面图片...')
      console.log('开始处理封面图片');
      try {
        // 压缩图片
        const compressedImage = await compressImage(coverImageFile.value, 1200, 1200, 0.8)
        ElMessage.info('正在上传封面图片...')
        const imageResponse = await uploadMeetingImage(compressedImage, String(props.meeting?.id || ''))
        updatedFormData.coverImage = imageResponse.data
      } catch (error) {
        console.error('图片压缩失败:', error)
        // 如果压缩失败，尝试直接上传原始图片
        ElMessage.info('正在上传原始封面图片...')
        const imageResponse = await uploadMeetingImage(coverImageFile.value, String(props.meeting?.id || ''))
        updatedFormData.coverImage = imageResponse.data
      }
    }
    
    // 2. 上传会议文件
    if (meetingFiles.value.length > 0) {
      ElMessage.info(`正在上传会议文件，共${meetingFiles.value.length}个...`)
      console.log(`准备上传${meetingFiles.value.length}个会议文件`);
      const filePromises = meetingFiles.value.map(file => 
        uploadMeetingFile(file, String(props.meeting?.id || ''))
      )
      const fileResponses = await Promise.all(filePromises)
      
      // 更新文件列表，只保留name和url
      updatedFormData.files = fileResponses.map((response, index) => ({
        name: meetingFiles.value[index].name,
        url: response.data
      })) as any;
    } else {
      console.log('没有会议文件需要上传');
      // 确保files属性存在，即使是空数组
      updatedFormData.files = [];
    }
    
    // 3. 上传视频
    console.log('准备检查视频上传, meetingVideos数组状态:', meetingVideos.value.length > 0 ? '有文件' : '为空');
    if (meetingVideos.value.length > 0) {
      // 只取第一个视频文件（因为限制了只能上传一个）
      const videoFile = meetingVideos.value[0];
      console.log('视频文件详细信息:', {
        name: videoFile.name,
        type: videoFile.type,
        size: videoFile.size,
        lastModified: videoFile.lastModified
      });
      ElMessage.info('正在上传会议视频...')
      try {
        const meetId = String(props.meeting?.id || '');
        console.log('上传视频到会议ID:', meetId);
        
        const videoResponse = await uploadMeetingVideo(videoFile, meetId)
        console.log('视频上传响应:', videoResponse);
        updatedFormData.videoUrl = videoResponse.data
        console.log('视频URL已设置:', updatedFormData.videoUrl);
      } catch (error) {
        console.error('视频上传失败，详细错误:', error);
        ElMessage.error(`视频上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    } else {
      // 确保videoUrl存在，即使是空字符串
      updatedFormData.videoUrl = updatedFormData.videoUrl || '';
      console.log('没有新视频需要上传，当前videoUrl:', updatedFormData.videoUrl || '空');
    }
    
    return updatedFormData
  } catch (error) {
    console.error('文件上传失败:', error)
    throw new Error('文件上传失败')
  }
}

// 修改handleSubmit方法，添加调试日志
const handleSubmit = async () => {
  if (!formRef.value) return
  
  console.log('提交表单，检查视频状态:', meetingVideos.value.length > 0 ? '有视频文件' : '无视频文件');
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 先上传所有文件
        const hasFilesToUpload = coverImageFile.value || meetingFiles.value.length > 0 || meetingVideos.value.length > 0
        console.log('表单验证通过，文件上传状态:', {
          hasCoverImage: !!coverImageFile.value,
          filesCount: meetingFiles.value.length,
          hasVideos: meetingVideos.value.length
        });
        
        let submitData: Partial<Meeting>
        
        if (hasFilesToUpload) {
          // 如果有文件需要上传，先上传文件
          console.log('有文件需要上传，开始上传流程');
          submitData = await uploadFilesAndGetFormData()
          console.log('文件上传完成，准备提交数据');
        } else {
          // 没有文件需要上传，直接使用当前表单数据，并简化文件列表
          console.log('无需上传文件，直接准备提交数据');
          submitData = {
            name: formData.value.name,
            type: formData.value.type,
            begin: formData.value.begin,
            end: formData.value.end,
            timeRange: formData.value.begin && formData.value.end ? 
                      `${formData.value.begin},${formData.value.end}` : undefined,
            location: formData.value.location,
            description: formData.value.description,
            isOnline: formData.value.isOnline,  // 保留原始引用，后面会转换为数字
            coverImage: formData.value.coverImage || '',
            files: convertToSimpleMeetingFiles(formData.value.files) as any,
            agenda: formData.value.agenda,
            videoUrl: formData.value.videoUrl || ''
          }
        }
        
        // 最终提交前再次检查视频URL
        console.log('提交前最终数据检查 - videoUrl:', submitData.videoUrl || '空');
        
        // 最终检查，确保所有字段格式符合要求
        // 确保文件只有name和url属性
        if (submitData.files && submitData.files.length > 0) {
          submitData.files = submitData.files.map(file => ({
            name: file.name,
            url: file.url
          })) as any;
        } else {
          submitData.files = [] as any;
        }
        
        // 确保videoUrl存在
        submitData.videoUrl = submitData.videoUrl || '';
        
        // 将isOnline从布尔值转换为数字（0或1）
        if (submitData.isOnline !== undefined) {
          // @ts-ignore - 类型错误可以忽略，因为API期望的可能是数字
          submitData.isOnline = submitData.isOnline ? 1 : 0;
          console.log('isOnline已转换为数字:', submitData.isOnline);
        }
        
        emit('submit', submitData)
      } catch (error) {
        console.error('表单提交失败:', error)
        ElMessage.error('表单提交失败: ' + (error instanceof Error ? error.message : '未知错误'))
      }
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

// 扩展UploadFile接口，添加类型属性
interface ExtendedUploadFile extends UploadFile {
  type?: string
}

// 修改图片上传处理函数
const handleCoverImageChange = (file: ExtendedUploadFile) => {
  console.log('图片文件信息:', file)
  
  // 优化文件类型检查，同时检查MIME类型和文件扩展名
  const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif']
  const fileName = file.name || ''
  const extension = fileName.split('.').pop()?.toLowerCase() || ''
  const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif']
  
  // 只要满足一种检查方式就通过
  const isValidType = allowedMimeTypes.includes(file.type || '') || 
                      allowedExtensions.includes(extension)
                      
  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片')
    return false
  }
  
  // 检查文件大小，改为更小的限制（2MB）
  const maxSize = 2 * 1024 * 1024 // 2MB
  if (file.size && file.size > maxSize) {
    ElMessage.error('图片大小不能超过 2MB，请压缩后再上传')
    return false
  }
  
  // 检查图片尺寸
  if (file.raw) {
    const rawFile = file.raw as File;
    return new Promise((resolve) => {
      const reader = new FileReader()
      reader.readAsDataURL(rawFile)
      reader.onload = (e) => {
        const image = new Image()
        image.src = e.target?.result as string
        image.onload = () => {
          // 最大限制宽高各为1600px
          if (image.width > 1600 || image.height > 1600) {
            ElMessage.error('图片尺寸过大，宽高应不超过1600px，请调整后再上传')
            resolve(false)
          } else {
            console.log('图片验证通过:', file.name, 'MIME类型:', file.type, '扩展名:', extension)
            coverImageFile.value = rawFile
            
            // 创建临时URL用于预览
            formData.value.coverImage = URL.createObjectURL(rawFile)
            resolve(true)
          }
        }
      }
    })
  }
  
  return false
}

// 图片删除处理
const handleCoverImageRemove = () => {
  coverImageFile.value = null
  formData.value.coverImage = ''
}

// 图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  if (file.url) {
    previewUrl.value = file.url
    previewVisible.value = true
  }
}

// 添加初始化完成后的日志
console.log('MeetingForm组件初始化完成，props.meeting:', props.meeting ? `ID: ${props.meeting.id}` : '新建会议');
</script>

<style scoped>
.meeting-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.meeting-cover-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration);
}

.meeting-cover-upload:hover {
  border-color: var(--el-color-primary);
}

.cover-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

.meeting-file-upload {
  margin-top: 8px;
}

:deep(.el-upload-list) {
  margin-top: 8px;
}

.agenda-section {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 16px;
}

.agenda-header {
  margin-bottom: 16px;
}

.mx-2 {
  margin: 0 8px;
}

:deep(.el-table) {
  margin-top: 16px;
}

.video-upload-section {
  display: flex;
  align-items: center;
}

.video-preview {
  margin-left: 16px;
}
</style> 